const express = require('express');
const cookieParser = require('cookie-parser');
const cors = require("cors");
const app = express();
const { expressjwt } = require("express-jwt");
const config = require("./routes/config");

const http = require("http").createServer(app); // 引入 http 模块
const setupSocket = require("./routes/socket"); // 引入 socket.js 文件
setupSocket(http);

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(function (req, res, next) {
  res.response = function (err, code = 1) {
    res.send({
      code,
      message: err instanceof Error ? err.message : err,
    });
  };
  next();
});
app.use("/public/", express.static("./public"));
const excludedPaths = [
  /\/api\/admin\/login/,
  /\/api\/user\/login/,
  /\/api\/user\/register/,
  /\/api\/carousel\/list/,
  /\/api\/category\/list/,
  /\/api\/goods\/list/,
  /\/api\/upload/,
];
app.use(
  expressjwt({ secret: config.jwtSecretKey, algorithms: ["HS256"] }).unless({
    path: excludedPaths,
  })
);

const upload = require('./routes/upload/index');
const admin = require('./routes/admin/index');
const carousel = require('./routes/carousel/index');
const category = require("./routes/category");
const goods = require("./routes/goods/index");
const user = require('./routes/user/index');
const feedback = require('./routes/feedback/index');
const chatHistory = require('./routes/chat_history/index');
const chatList = require('./routes/chat_list/index');
// 注册路由
app.use('/api', admin, user, carousel, feedback, category, goods, upload, chatList, chatHistory);
app.use(function (err, req, res, next) {
  if (err.name === "UnauthorizedError")
    return res.response("身份认证失败", 401);
  res.response(err);
});


http.listen(3535, function () {
  console.log("服务端已运行： http://127.0.0.1:3535");
});
